package com.mazaiting.mybatisplus.config;

import com.mazaiting.mybatisplus.encrypt.IEncryptor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 获取配置文件配置
 * 初始化 参数
 * @author danghailiang
 */
@ConfigurationProperties(prefix = "mybatis-crypto")
public class MybatisCryptoProperties {

    /**
     * 配置文件前缀
     * 使用 Param 注解时指定参数名称
     */
    private List<String> mappedKeyPrefixes = new ArrayList<>();
    /**
     * 快速失败
     * true: 直接抛出异常
     * false: 不抛出异常
     */
    private boolean failFast = true;
    /**
     * 默认签名
     */
    private String key = "5ZOG5ZWmQeaipjEyMzQ1Ng==";
    /**
     * 默认加密处理器
     */
    private Class<? extends IEncryptor> encryptor = com.mazaiting.mybatisplus.encrypt.encryptor.BasicTextEncryptor.class;
    /**
     * 配置类服务
     */
    private MybatisCryptoConfig mybatisCryptoConfig;

    public Class<? extends IEncryptor> getEncryptor() {
        return encryptor;
    }

    public void setEncryptor(Class<? extends IEncryptor> encryptor) {
        this.encryptor = encryptor;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public boolean isFailFast() {
        return failFast;
    }

    public void setFailFast(boolean failFast) {
        this.failFast = failFast;
    }

    public List<String> getMappedKeyPrefixes() {
        return mappedKeyPrefixes;
    }

    public void setMappedKeyPrefixes(List<String> mappedKeyPrefixes) {
        this.mappedKeyPrefixes = mappedKeyPrefixes;
    }

    /**
     * 校验key与加密器是否为空
     */
    @PostConstruct
    public void validate() {
        // 判断key是否为空, 为空则抛出异常
        if (!StringUtils.hasLength(key)) {
            throw new IllegalStateException("丢失mybatis.crypto.key配置");
        }
        // 判断加密器是否为空
        if (Objects.isNull(encryptor)) {
            throw new IllegalStateException("丢失mybatis.crypto.encryptor配置");
        }
    }

    /**
     * 初始化MybatisCryptoConfig配置参数
     *
     * @return mybatisCryptoConfig对象
     */
    public MybatisCryptoConfig toMybatisCryptoConfig() {
        if (mybatisCryptoConfig == null) {
            mybatisCryptoConfig = new MybatisCryptoConfig(this.mappedKeyPrefixes, this.failFast,
                    this.key, this.encryptor);
        }
        return mybatisCryptoConfig;
    }
}
